import dayjs from "dayjs";
import isSameOrAfter from "dayjs/plugin/isSameOrAfter";
import isSameOrBefore from "dayjs/plugin/isSameOrBefore";
import isBetween from "dayjs/plugin/isBetween";
import qrCode from "./qrcode";

dayjs.extend(isSameOrAfter);
dayjs.extend(isSameOrBefore);
dayjs.extend(isBetween);

let type = process.env.VUE_APP_API_ENV === "dev" ? "dev" : "production";
let url = {
  dev: "https://zhuanti.qa.chebada.com/activityapi/Handler/",
  production: "https://zhuanti.chebada.com/activityapi/Handler/",
  t: "https://zhuanti.t.chebada.com/activityapi/Handler/",
  local: ""
};
let isCBD = navigator.userAgent.indexOf("chebada") != -1;

/**
 * 公用ajax组件
 * param为请求参数body,没有则传{};
 * handler接口名;
 * serviceName服务名;
 * Created by wusk on 19/12/13.
 */
function sendRequest(param, handler, serviceName) {
  let postUrl = url[type] + handler;
  return new Promise((resolve, reject) => {
    $.ajax({
      dataType: "json",
      url: postUrl,
      type: "post",
      timeout: "8000",
      data: JSON.stringify({
        header: {
          serviceName: serviceName
        },
        body: param
      }),
      beforeSend: function() {
        cbdztUtil.Toast.showLoading();
      },
      success: function(res) {
        cbdztUtil.Toast.hideLoading();
        resolve(res);
      },
      error: function(error) {
        cbdztUtil.Toast.hideLoading();
        reject(error);
      }
    });
  });
}

function isIOS() {
  if (isCBD) {
    bridge.userInfoPlugins.getSystemInfo().then(res => {
      var ios = res.clientInfo.osType;
      if (ios === "ios") {
        return true;
      }
    });
  }
  return false;
}

async function getEnv() {
  return new Promise(resolve => {
    const isCBD = navigator.userAgent.indexOf("chebada") != -1;
    const isWX =
      navigator.userAgent.toLowerCase().indexOf("micromessenger") > -1;
    if (isCBD) resolve("cbd");
    else if (!isWX) resolve("h5");
    else {
      try {
        wx.miniProgram.getEnv(res => {
          if (res.miniprogram) {
            resolve("mini");
          } else {
            resolve("wx");
          }
        });
      } catch (err) {
        resolve("wx");
      }
    }
  });
}

const isFunction = func =>
  Object.prototype.toString.call(func) === "[object Function]";

// cbdFunc, miniFunc, h5Func 分别为app, 小程序, web中调用的函数
const envFunc = async (cbdFunc, miniFunc, h5Func) => {
  const env = await getEnv();

  if (env === "cbd") isFunction(cbdFunc) && cbdFunc();
  else if (env === "mini") isFunction(miniFunc) && miniFunc();
  else if (env === "h5") isFunction(h5Func) && h5Func();
};

// 分享小程序(app)
const activityShare = async params => {
  const { title, shareUrl, shareImg, path, imgUrl } = params;

  const shareParams = {
    paramList: [
      {
        shareTo: "1",
        title,
        shareUrl: shareUrl,
        miniProgram: {
          webPageUrl: shareUrl,
          userName: "gh_0aacaec14151",
          path
        },
        contentType: "8",
        thumbnail: shareImg,
        summary: ""
      },
      {
        shareTo: "2",
        title: "巴士管家",
        shareUrl: imgUrl,
        miniProgram: {
          webPageUrl: "",
          userName: "",
          path: ""
        },
        contentType: "9",
        thumbnail: imgUrl
      }
    ]
  };

  try {
    bridge.utilsPlugins.startShare(shareParams);
  } catch (e) {
    bridge.utilsPlugins.toast("您还未安装微信");
  }
};

// 分享小程序(mini)
const shareInwx = params => {
  const { shareUrl, title, imageUrl } = params;

  wx.miniProgram.postMessage({
    data: {
      shareInfo: {
        path: shareUrl,
        title,
        imageUrl
      },
      path: shareUrl,
      shareUrl,
      title,
      imageUrl
    }
  });
};

// 活动结束(app, mini, h5)
const activityEnd = async () => {
  const env = await getEnv();

  if (env === "cbd") {
    // bridge.naviPlugins.openWebPage({
    //   webPageUrl: "https://zhuanti.chebada.com/act/app/2020/11/activitiesend/"
    // });
    document.location.replace(
      "https://zhuanti.chebada.com/act/app/2020/11/activitiesend/"
    );
  } else if (env === "mini") {
    wx.miniProgram.redirectTo({
      url: "/pages/common/activities-end/activities-end"
    });
  } else {
    window.location.href =
      "https://zhuanti.chebada.com/act/app/2020/11/activitiesend/";
  }
};

// 去红包列表(app, mini)
const toRedPocket = async () => {
  const env = await getEnv();
  if (env === "cbd") {
    bridge.naviPlugins.openWebPage({
      webPageUrl: "cbdbusbutler://GTPRedPacket/Home"
    });
  } else if (env === "mini") {
    wx.miniProgram.navigateTo({
      url: "/pages/common/redPackage/redPackage"
    });
  }
};

// 用户将打开推送(app)
const openPushInfo = (modalInfo, cb) => {
  const { des, leftText, rightText } = modalInfo;
  const data = {
    des,
    leftText,
    rightText,
    rightFun() {
      bridge.utilsPlugins
        .isAuthorizedPushService()
        .then(async res => {
          if (res.enabled == 0) {
            // 未打开，跳转设置
            const data = {
              des: "需开启推送功能才能及时收到提醒",
              leftText: "取消",
              rightText: "去开启",
              rightFun() {
                bridge.utilsPlugins.openAppSetting();
              }
            };
            cbdztUtil.ztAlertDialog(data);
          } else {
            cb();
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
  };
  cbdztUtil.ztAlertDialog(data);
};

// 用户将关闭推送(app)
const closePushInfo = (modalInfo, cb) => {
  const { des, leftText, rightText } = modalInfo;
  const data = {
    des,
    leftText,
    rightText,
    rightFun: async () => {
      cb();
    }
  };
  cbdztUtil.ztAlertDialog(data);
};

// 右上角分享 (app)
const appShareOnRightBtn = async params => {
  const { title, shareImg, path, shareUrl, imgUrl } = params;

  bridge.naviPlugins.setShare({
    paramList: [
      {
        shareTo: "1",
        title,
        shareUrl,
        miniProgram: {
          webPageUrl: shareUrl,
          userName: "gh_0aacaec14151",
          path
        },
        contentType: "8",
        thumbnail: shareImg,
        summary: ""
      },
      {
        shareTo: "2",
        title: "巴士管家",
        shareUrl: imgUrl,
        miniProgram: {
          webPageUrl: "",
          userName: "",
          path: ""
        },
        contentType: "9",
        thumbnail: imgUrl
      }
    ],
    sharedCallback: "",
    eventId: "",
    eventParams: ""
  });
};

// 小程序跳转网页
const toWxWeb = url => {
  wx.miniProgram.navigateTo({ url });
};

// 小程序打开h5
const getWxPage = url => {
  return `pages/web/web?url=${encodeURIComponent(url)}`;
};

const getUrlParam = name => {
  const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
  const r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return decodeURIComponent(r[2]);
  }
  return null;
};

// 获取url参数
const getQuery = val => {
  if (getUrlParam(val)) return getUrlParam(val);
  const w = location.hash.indexOf("?");
  const query = location.hash.substring(w + 1);

  const vars = query.split("&");
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split("=");
    if (pair[0] == val) {
      return pair[1];
    }
  }

  return false;
};

// 获取小程序路由跳转的参数
const getRouteParamsMini = () => {
  const isskey = getQuery("isskey");
  const sessionCode = getQuery("sessionCode");
  const isbind = getQuery("isbind");
  const mobileNo = getQuery("mobileNo");
  const uuid = getQuery("uuid");

  return {
    isskey,
    sessionCode,
    isbind,
    mobileNo,
    uuid
  };
};

// 0 [startDate, middleDate)
// 1 [middleDate, endDate)
const timeIsBetween = (currentDate, startDate, middleDate) => {
  let currentDateUtil = dayjs(currentDate);
  let startDateUtil = dayjs(startDate);
  let middleDateUtil = dayjs(middleDate);
  // let endDateUtil = dayjs(endDate);

  if (
    currentDateUtil.isSameOrAfter(startDateUtil, "day") &&
    currentDateUtil.isSameOrBefore(middleDateUtil, "day")
  )
    return true;
  else return false;
};

// 开始时间A 结束时间B 来 算出A-B之间时间的数组
const timeGapArr = (startDate, endDate) => {
  let timeArr = [];
  let length = dayjs(endDate).diff(startDate, "day");
  let time = null;

  for (let i = 0; i <= length; i++) {
    time = dayjs(startDate).add(i, "day");
    if (time.isBetween(startDate, endDate, "day", "[]")) {
      timeArr.push(time.format("YYYY-MM-DD"));
      continue;
    }
    break;
  }

  return timeArr;
};

// 时间格式化
const timeFormat = (val, format) => dayjs(val).format(format);

// 图片转base64
const convertImgToBase64 = img => {
  if (!document) return;
  let canvas = document.createElement("CANVAS");
  canvas.width = img.width;
  canvas.height = img.height;
  let ctx = canvas.getContext("2d");

  ctx.drawImage(img, 0, 0, img.width, img.height);
  return canvas.toDataURL("image/png");
};

// file对象转base64
const fileToBase64 = file => {
  return new Promise((resolve, reject) => {
    try {
      let reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = e => {
        return resolve(e);
      };
      reader.onerror = e => {
        return reject(e);
      };
    } catch (e) {
      return reject(e);
    }
  });
};

// 判断时间 是否在某个时间端 的位置
// 0 startTime之前
// 1 endTime 之后
// 2 [startTime, endTime] 之间
const isBeforeOrAfterGap = (currentTime, startTime, endTime) => {
  let currentTimeUtil = dayjs(currentTime);
  let startTimeUtil = dayjs(startTime);
  let endTimeUtil = dayjs(endTime);

  if (currentTimeUtil.isBefore(startTimeUtil, "day")) return 0;
  else if (currentTimeUtil.isAfter(endTimeUtil, "day")) return 1;
  else return 2;
};

// 画canvas
const drawCanvas = async (imageUrl, params, axisX, axisy) => {
  try {
    let qrcode = await qrCode(params);
    let canvas = document.createElement("canvas");
    let img = await loadImg(imageUrl);
    let qrimg = await loadImg(qrcode);

    const { width, height } = img;
    canvas.width = width;
    canvas.height = height;
    let ctx = canvas.getContext("2d");

    ctx.drawImage(img, 0, 0, width, height);
    ctx.drawImage(qrimg, axisX, axisy, 180, 180);

    return canvas.toDataURL();
  } catch (e) {
    console.log(e, "errr");
  }
};

const loadImg = imageUrl => {
  return new Promise((resolve, reject) => {
    let img = new Image();
    img.crossOrigin = "Anonymous";
    img.src = imageUrl;
    img.onload = () => {
      resolve(img);
    };

    img.onerror = err => reject(err);
  });
};

export {
  sendRequest,
  getUrlParam,
  isIOS,
  getEnv,
  envFunc,
  activityShare,
  shareInwx,
  activityEnd,
  toRedPocket,
  openPushInfo,
  closePushInfo,
  appShareOnRightBtn,
  toWxWeb,
  getWxPage,
  getQuery,
  timeIsBetween,
  timeGapArr,
  timeFormat,
  convertImgToBase64,
  fileToBase64,
  isBeforeOrAfterGap,
  isSameOrAfter,
  drawCanvas,
  getRouteParamsMini,
  loadImg
};
